import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Input } from './ui/input';
import { Calculator, Clock, Trophy, Star } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface MathTestProps {
  onComplete: (result: TestResult) => void;
}

interface MathQuestion {
  id: number;
  type: 'arithmetic' | 'algebra' | 'geometry' | 'percentage' | 'fraction' | 'word_problem';
  question: string;
  answer: number;
  choices?: number[];
  difficulty: 'easy' | 'medium' | 'hard';
  timeLimit: number; // 秒
}

export function MathTest({ onComplete }: MathTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [questions, setQuestions] = useState<MathQuestion[]>([]);
  const [userAnswer, setUserAnswer] = useState('');
  const [responses, setResponses] = useState<{ answer: number; correct: boolean; time: number }[]>([]);
  const [timeLeft, setTimeLeft] = useState(600); // 10分钟总时间
  const [questionTimeLeft, setQuestionTimeLeft] = useState(0);
  const [startTime, setStartTime] = useState<number>(0);
  const [questionStartTime, setQuestionStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);
  const [feedbackAnswer, setFeedbackAnswer] = useState(0);

  const TOTAL_QUESTIONS = 20;

  // 动态生成数学题目
  const generateQuestions = (): MathQuestion[] => {
    const questions: MathQuestion[] = [];
    let questionId = 1;

    // 基础算术题 (6道)
    for (let i = 0; i < 6; i++) {
      questions.push(generateArithmeticQuestion(questionId++));
    }

    // 代数题 (4道)
    for (let i = 0; i < 4; i++) {
      questions.push(generateAlgebraQuestion(questionId++));
    }

    // 几何题 (3道)
    for (let i = 0; i < 3; i++) {
      questions.push(generateGeometryQuestion(questionId++));
    }

    // 百分比题 (3道)
    for (let i = 0; i < 3; i++) {
      questions.push(generatePercentageQuestion(questionId++));
    }

    // 分数题 (2道)
    for (let i = 0; i < 2; i++) {
      questions.push(generateFractionQuestion(questionId++));
    }

    // 应用题 (2道)
    for (let i = 0; i < 2; i++) {
      questions.push(generateWordProblem(questionId++));
    }

    // 随机打乱顺序
    return questions.sort(() => Math.random() - 0.5);
  };

  const generateArithmeticQuestion = (id: number): MathQuestion => {
    const operations = ['+', '-', '×', '÷'];
    const operation = operations[Math.floor(Math.random() * operations.length)];
    
    let a: number, b: number, answer: number, question: string;
    
    switch (operation) {
      case '+':
        a = Math.floor(Math.random() * 500) + 10;
        b = Math.floor(Math.random() * 500) + 10;
        answer = a + b;
        question = `${a} + ${b} = ?`;
        break;
      case '-':
        a = Math.floor(Math.random() * 500) + 100;
        b = Math.floor(Math.random() * (a - 10)) + 10;
        answer = a - b;
        question = `${a} - ${b} = ?`;
        break;
      case '×':
        a = Math.floor(Math.random() * 25) + 5;
        b = Math.floor(Math.random() * 25) + 5;
        answer = a * b;
        question = `${a} × ${b} = ?`;
        break;
      case '÷':
        answer = Math.floor(Math.random() * 50) + 5;
        b = Math.floor(Math.random() * 20) + 2;
        a = answer * b;
        question = `${a} ÷ ${b} = ?`;
        break;
      default:
        a = 10; b = 5; answer = 15; question = '10 + 5 = ?';
    }

    return {
      id,
      type: 'arithmetic',
      question,
      answer,
      difficulty: answer > 500 ? 'hard' : answer > 100 ? 'medium' : 'easy',
      timeLimit: 30
    };
  };

  const generateAlgebraQuestion = (id: number): MathQuestion => {
    const types = [
      'linear_equation',
      'quadratic_simple',
      'substitution',
      'factoring'
    ];
    
    const type = types[Math.floor(Math.random() * types.length)];
    
    switch (type) {
      case 'linear_equation':
        const x = Math.floor(Math.random() * 20) + 1;
        const a = Math.floor(Math.random() * 10) + 2;
        const b = Math.floor(Math.random() * 50) + 10;
        const result = a * x + b;
        return {
          id,
          type: 'algebra',
          question: `如果 ${a}x + ${b} = ${result}，那么 x = ?`,
          answer: x,
          difficulty: a > 5 ? 'medium' : 'easy',
          timeLimit: 45
        };
        
      case 'quadratic_simple':
        const root = Math.floor(Math.random() * 10) + 1;
        const constant = root * root;
        return {
          id,
          type: 'algebra',
          question: `x² = ${constant}，那么正数解 x = ?`,
          answer: root,
          difficulty: 'medium',
          timeLimit: 45
        };
        
      case 'substitution':
        const val = Math.floor(Math.random() * 10) + 1;
        const coeff = Math.floor(Math.random() * 5) + 2;
        const add = Math.floor(Math.random() * 20) + 5;
        const ans = coeff * val + add;
        return {
          id,
          type: 'algebra',
          question: `如果 y = ${coeff}x + ${add}，当 x = ${val} 时，y = ?`,
          answer: ans,
          difficulty: 'easy',
          timeLimit: 30
        };
        
      default:
        return {
          id,
          type: 'algebra',
          question: '2x + 3 = 11，那么 x = ?',
          answer: 4,
          difficulty: 'easy',
          timeLimit: 30
        };
    }
  };

  const generateGeometryQuestion = (id: number): MathQuestion => {
    const types = ['rectangle_area', 'circle_area', 'triangle_area', 'perimeter'];
    const type = types[Math.floor(Math.random() * types.length)];
    
    switch (type) {
      case 'rectangle_area':
        const length = Math.floor(Math.random() * 15) + 5;
        const width = Math.floor(Math.random() * 15) + 5;
        return {
          id,
          type: 'geometry',
          question: `一个长方形的长为 ${length} 厘米，宽为 ${width} 厘米，面积是多少平方厘米？`,
          answer: length * width,
          difficulty: 'easy',
          timeLimit: 35
        };
        
      case 'circle_area':
        const radius = Math.floor(Math.random() * 10) + 3;
        const area = Math.round(Math.PI * radius * radius);
        return {
          id,
          type: 'geometry',
          question: `一个圆的半径为 ${radius} 厘米，面积约为多少平方厘米？（π ≈ 3.14）`,
          answer: area,
          difficulty: 'medium',
          timeLimit: 45
        };
        
      case 'triangle_area':
        const base = Math.floor(Math.random() * 20) + 6;
        const height = Math.floor(Math.random() * 15) + 4;
        return {
          id,
          type: 'geometry',
          question: `一个三角形的底为 ${base} 厘米，高为 ${height} 厘米，面积是多少平方厘米？`,
          answer: (base * height) / 2,
          difficulty: 'easy',
          timeLimit: 40
        };
        
      default:
        const side = Math.floor(Math.random() * 15) + 5;
        return {
          id,
          type: 'geometry',
          question: `一个正方形的边长为 ${side} 厘米，周长是多少厘米？`,
          answer: side * 4,
          difficulty: 'easy',
          timeLimit: 25
        };
    }
  };

  const generatePercentageQuestion = (id: number): MathQuestion => {
    const types = ['percentage_of', 'percentage_increase', 'discount'];
    const type = types[Math.floor(Math.random() * types.length)];
    
    switch (type) {
      case 'percentage_of':
        const total = Math.floor(Math.random() * 500) + 100;
        const percentage = [10, 20, 25, 30, 40, 50, 75][Math.floor(Math.random() * 7)];
        const result = (total * percentage) / 100;
        return {
          id,
          type: 'percentage',
          question: `${total} 的 ${percentage}% 是多少？`,
          answer: result,
          difficulty: percentage > 50 ? 'medium' : 'easy',
          timeLimit: 35
        };
        
      case 'percentage_increase':
        const original = Math.floor(Math.random() * 200) + 50;
        const increase = [10, 15, 20, 25, 30][Math.floor(Math.random() * 5)];
        const increased = original * (1 + increase / 100);
        return {
          id,
          type: 'percentage',
          question: `一个数是 ${original}，增加 ${increase}% 后是多少？`,
          answer: increased,
          difficulty: 'medium',
          timeLimit: 40
        };
        
      default:
        const price = Math.floor(Math.random() * 300) + 100;
        const discount = [10, 15, 20, 25, 30][Math.floor(Math.random() * 5)];
        const finalPrice = price * (1 - discount / 100);
        return {
          id,
          type: 'percentage',
          question: `原价 ${price} 元的商品打 ${100 - discount} 折，现价是多少元？`,
          answer: finalPrice,
          difficulty: 'medium',
          timeLimit: 40
        };
    }
  };

  const generateFractionQuestion = (id: number): MathQuestion => {
    const types = ['fraction_add', 'fraction_multiply'];
    const type = types[Math.floor(Math.random() * types.length)];
    
    if (type === 'fraction_add') {
      // 同分母分数加法
      const denominator = [4, 6, 8, 10, 12][Math.floor(Math.random() * 5)];
      const num1 = Math.floor(Math.random() * (denominator - 1)) + 1;
      const num2 = Math.floor(Math.random() * (denominator - num1)) + 1;
      const sum = num1 + num2;
      
      return {
        id,
        type: 'fraction',
        question: `${num1}/${denominator} + ${num2}/${denominator} = ? （用最简分数表示，如果是整数就填整数）`,
        answer: sum === denominator ? 1 : sum,
        difficulty: 'easy',
        timeLimit: 45
      };
    } else {
      // 分数乘整数
      const numerator = Math.floor(Math.random() * 5) + 1;
      const denominator = [4, 6, 8][Math.floor(Math.random() * 3)];
      const multiplier = Math.floor(Math.random() * 4) + 2;
      const result = (numerator * multiplier) / denominator;
      
      return {
        id,
        type: 'fraction',
        question: `${numerator}/${denominator} × ${multiplier} = ? （小数形式）`,
        answer: Math.round(result * 100) / 100,
        difficulty: 'medium',
        timeLimit: 50
      };
    }
  };

  const generateWordProblem = (id: number): MathQuestion => {
    const problems = [
      {
        question: '小明买了3支笔，每支12元，又买了2本书，每本25元。他总共花了多少钱？',
        answer: 3 * 12 + 2 * 25
      },
      {
        question: '一辆车每小时行驶80公里，行驶了3.5小时，总共行驶了多少公里？',
        answer: 80 * 3.5
      },
      {
        question: '学校有480名学生，其中3/8是女生，女生有多少人？',
        answer: 480 * 3 / 8
      },
      {
        question: '一个长方形的周长是36米，长是12米，宽是多少米？',
        answer: (36 - 12 * 2) / 2
      },
      {
        question: '商店原价100元的商品打8折销售，顾客实际支付多少元？',
        answer: 100 * 0.8
      }
    ];

    const selectedProblem = problems[Math.floor(Math.random() * problems.length)];
    
    return {
      id,
      type: 'word_problem',
      question: selectedProblem.question,
      answer: selectedProblem.answer,
      difficulty: 'medium',
      timeLimit: 60
    };
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
        
        setQuestionTimeLeft(prev => {
          if (prev <= 1 && !showFeedback) {
            // 时间到，自动提交空答案
            handleSubmit();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft, showFeedback]);

  useEffect(() => {
    if (stage === 'test' && questions.length > 0) {
      setQuestionTimeLeft(questions[currentQuestion].timeLimit);
      setQuestionStartTime(Date.now());
    }
  }, [currentQuestion, stage]);

  const handleStartTest = () => {
    const generatedQuestions = generateQuestions();
    setQuestions(generatedQuestions);
    setStage('test');
    setStartTime(Date.now());
    setQuestionStartTime(Date.now());
    setQuestionTimeLeft(generatedQuestions[0]?.timeLimit || 30);
  };

  const handleSubmit = () => {
    const question = questions[currentQuestion];
    const userNum = parseFloat(userAnswer) || 0;
    const correct = Math.abs(userNum - question.answer) < 0.01; // 允许小数误差
    const reactionTime = Date.now() - questionStartTime;
    
    setResponses(prev => [...prev, {
      answer: userNum,
      correct,
      time: reactionTime
    }]);
    
    if (correct) {
      setScore(prev => prev + 1);
    }
    
    // 显示反馈
    setFeedbackCorrect(correct);
    setFeedbackAnswer(question.answer);
    setShowFeedback(true);
    
    setTimeout(() => {
      setShowFeedback(false);
      setUserAnswer('');
      
      if (currentQuestion < questions.length - 1) {
        setCurrentQuestion(prev => prev + 1);
      } else {
        setStage('results');
      }
    }, 1500);
  };

  const handleComplete = () => {
    const totalQuestions = questions.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalQuestions) * 100);
    const averageTime = Math.round(
      responses.reduce((sum, r) => sum + r.time, 0) / responses.length
    );
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 按题目类型分类统计
    const typeStats: { [key: string]: { correct: number; total: number } } = {};
    
    questions.forEach((question, index) => {
      const type = question.type;
      if (!typeStats[type]) {
        typeStats[type] = { correct: 0, total: 0 };
      }
      typeStats[type].total++;
      if (responses[index]?.correct) {
        typeStats[type].correct++;
      }
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'math',
      score: accuracy,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalQuestions,
        correctAnswers,
        accuracy,
        averageTimePerQuestion: averageTime,
        typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
          type: type === 'arithmetic' ? '基础运算' :
                type === 'algebra' ? '代数' :
                type === 'geometry' ? '几何' :
                type === 'percentage' ? '百分比' :
                type === 'fraction' ? '分数' : '应用题',
          accuracy: stats.total > 0 ? Math.round((stats.correct / stats.total) * 100) : 0,
          correct: stats.correct,
          total: stats.total
        })),
        questionsGenerated: questions.map(q => ({ type: q.type, difficulty: q.difficulty }))
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-blue-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-blue-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Calculator className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">数学计算测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的数学计算和逻辑思维能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-blue-50 to-cyan-50 rounded-xl p-6 border border-blue-100">
              <h3 className="font-semibold text-blue-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>本测试包含20道数学题，每次动态生成不同题目</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>涵盖算术、代数、几何、百分比、分数、应用题等</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>每题有时间限制，需要快速准确地计算</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-blue-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>输入数字答案，支持小数（如3.14）</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2">基础运算</h4>
                <p className="text-sm text-green-700">加减乘除四则运算</p>
              </div>
              <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
                <h4 className="font-semibold text-purple-800 mb-2">代数几何</h4>
                <p className="text-sm text-purple-700">方程求解和图形计算</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200">
                <div className="text-2xl font-bold text-blue-600 mb-1">动态</div>
                <div className="text-sm text-blue-700">题目生成</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div className="text-2xl font-bold text-cyan-600 mb-1">20</div>
                <div className="text-sm text-cyan-700">题目数量</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-cyan-50 rounded-xl border border-blue-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">10</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-blue-600 to-cyan-500 hover:from-blue-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && questions.length > 0) {
    const question = questions[currentQuestion];
    const progress = (currentQuestion / questions.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-blue-100 text-blue-700 border-blue-300">
              题目 {currentQuestion + 1} / {questions.length}
            </Badge>
            <Badge variant="outline" className={`${
              question.type === 'arithmetic' ? 'bg-green-100 text-green-700 border-green-300' :
              question.type === 'algebra' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              question.type === 'geometry' ? 'bg-orange-100 text-orange-700 border-orange-300' :
              question.type === 'percentage' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
              question.type === 'fraction' ? 'bg-pink-100 text-pink-700 border-pink-300' :
              'bg-indigo-100 text-indigo-700 border-indigo-300'
            }`}>
              {question.type === 'arithmetic' ? '基础运算' :
               question.type === 'algebra' ? '代数' :
               question.type === 'geometry' ? '几何' :
               question.type === 'percentage' ? '百分比' :
               question.type === 'fraction' ? '分数' : '应用题'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-4">
            <div className="text-center">
              <div className={`text-2xl font-bold font-mono ${questionTimeLeft <= 10 ? 'text-red-500' : 'text-blue-600'}`}>
                {questionTimeLeft}
              </div>
              <div className="text-xs text-slate-500">题目时间</div>
            </div>
            <div className="text-center">
              <div className="text-lg font-mono text-slate-600">
                {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
              </div>
              <div className="text-xs text-slate-500">总剩余</div>
            </div>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 问题区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-blue-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-xl text-slate-800">{question.question}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex gap-3">
              <Input
                type="number"
                step="any"
                value={userAnswer}
                onChange={(e) => setUserAnswer(e.target.value)}
                placeholder="输入您的答案..."
                className="text-lg font-mono text-center"
                disabled={showFeedback}
                onKeyPress={(e) => {
                  if (e.key === 'Enter' && userAnswer.trim() && !showFeedback) {
                    handleSubmit();
                  }
                }}
              />
              <Button
                onClick={handleSubmit}
                disabled={!userAnswer.trim() || showFeedback}
                className="bg-gradient-to-r from-blue-600 to-cyan-500 hover:from-blue-700 hover:to-cyan-600 text-white px-8"
              >
                提交
              </Button>
            </div>

            {question.type === 'fraction' && (
              <div className="text-sm text-slate-600 bg-slate-50 rounded-lg p-3">
                <strong>提示：</strong>分数题请按要求格式作答。如果答案是整数，直接填写整数；如果要求小数形式，填写小数。
              </div>
            )}
          </CardContent>
        </Card>

        {/* 反馈弹窗 */}
        <AnimatePresence>
          {showFeedback && (
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-md"
            >
              <Card className={`border-0 shadow-lg ${
                feedbackCorrect 
                  ? 'bg-green-500 text-white' 
                  : 'bg-red-500 text-white'
              }`}>
                <CardContent className="py-4 px-6">
                  <div className="text-center">
                    <div className="font-semibold mb-2">
                      {feedbackCorrect ? '正确！' : '答案错误'}
                    </div>
                    {!feedbackCorrect && (
                      <div className="text-sm opacity-90">
                        正确答案：{feedbackAnswer}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalQuestions = questions.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalQuestions) * 100);
    const averageTime = Math.round(
      responses.reduce((sum, r) => sum + r.time, 0) / responses.length
    );

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-blue-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-blue-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-blue-600 to-cyan-500 bg-clip-text text-transparent">
              {accuracy}
            </div>
            <p className="text-slate-600">数学计算准确率</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200">
                <div className="text-2xl font-bold text-blue-600 mb-1">{correctAnswers}/{totalQuestions}</div>
                <div className="text-sm text-blue-700">正确题数</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div className="text-2xl font-bold text-cyan-600 mb-1">{averageTime / 1000}s</div>
                <div className="text-sm text-cyan-700">平均用时</div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-blue-600 to-cyan-500 hover:from-blue-700 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}